package top.lingkang.finalvalidated.handle;

import top.lingkang.finalvalidated.core.FinalValidatorFactory;
import top.lingkang.finalvalidated.error.CheckException;
import top.lingkang.finalvalidated.error.ValidatedException;
import top.lingkang.finalvalidated.utils.FinalValidatorUtils;

import java.util.regex.Pattern;

/**
 * @author lingkang
 * Created by 2024/1/28
 */
public class PatternHandle extends ValidHandle {
    private final String errorStr;
    private final Pattern pattern;
    private final top.lingkang.finalvalidated.constraints.Pattern patternAnn;

    public PatternHandle(ValidVal validVal, top.lingkang.finalvalidated.constraints.Pattern patternAnn) {
        super(validVal, patternAnn);
        this.patternAnn = patternAnn;

        if (FinalValidatorUtils.isBlank(patternAnn.value())) {
            throw new CheckException("@Pattern 所配置的正则表达式(value)不能为空！字段属性：" + validVal.getName());
        }
        if (FinalValidatorUtils.isNotEmpty(patternAnn.message())) {
            errorStr = patternAnn.message();
        } else if (FinalValidatorUtils.isNotEmpty(validVal.getTag())) {
            errorStr = FinalValidatorFactory.message.getProperty("Pattern")
                    .replace("{attrName}", validVal.getTag());
        } else {
            errorStr = FinalValidatorFactory.message.getProperty("Pattern")
                    .replace("{attrName}", validVal.getName());
        }
        pattern = Pattern.compile(patternAnn.value());
    }

    @Override
    public void valid(Object target) {
        Object o = validVal.getValGet().get(target);
        if (o == null || !pattern.matcher(o.toString()).matches()) {
            throw new ValidatedException(errorStr, validVal);
        }
    }

    @Override
    public Class<?>[] getGroups() {
        return patternAnn.groups();
    }
}
